package com.dzl.timer;

import com.dzl.integral.service.WelfareIntegralGrantService;
import com.dzl.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 定时任务类
 * @author caobucao
 * @date 2021/5/26 15:32
 */
@Slf4j
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@Service
public class TimerTask {

    @Autowired
    private WelfareIntegralGrantService welfareIntegralGrantService;

    /**
     * 分发积分在设定时间自动到账
     * @date 2021/9/9 9:50
     * @author caobucao
     */
    @Async
    @Scheduled(cron = "0 */2 * * * ?") //2分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void integralGrantTimer() {
        //加锁  10秒
        boolean lock = RedisUtil.tryLock("UPDATE_INTEGRAL_GRANT_STATE:" , 10000);
        if(lock){
            log.info("-----------------------分发积分自动到账任务开始-----------------------");
            Integer count = welfareIntegralGrantService.updateIntegralGrantState();
            log.info("-----------------------分发积分自动到账任务，共分发到账 " + count + " 条积分，任务结束-----------------------");
            RedisUtil.unlock("UPDATE_INTEGRAL_GRANT_STATE");
        }else{
            log.info("-----------------------分发积分自动到账任务后台处理中--------------------------");
        }
    }

    /**
     * 积分过期定时任务
     * @date 2021/9/9 16:36
     * @author caobucao
     */
    @Async
//    @Scheduled(cron = "0 1 0 * * ?") //每天凌晨0点1分执行
    @Scheduled(cron = "0 */5 * * * ?") //5分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void integralExpiredTimer() {
        //加锁  10秒
        boolean lock = RedisUtil.tryLock("UPDATE_INTEGRAL_EXPIRED_STATE:" , 10000);
        if(lock){
            log.info("-----------------------积分过期任务开始-----------------------");
            Integer count = welfareIntegralGrantService.updateIntegralExpiredState();
            log.info("-----------------------积分过期任务结束，共过期 " + count + " 条积分，任务结束-----------------------");
            RedisUtil.unlock("UPDATE_INTEGRAL_EXPIRED_STATE");
        }else{
            log.info("-----------------------积分过期任务后台处理中--------------------------");
        }
    }

}
